﻿<%@ WebHandler Language="C#" Class="_wxcall" %>

using System;
using System.Web;
using System.Data;
using System.Xml;
using NS.Utilities;
using BLL;
using Model;
using WechatUtility;

public class _wxcall : IHttpHandler
{
    private string Token = WebConfigHelper.GetAppSet("Token");

    public void ProcessRequest(HttpContext context)
    {
        string postStr = "";
        if (context.Request.HttpMethod.ToLower() == "post")
        {
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            postStr = System.Text.Encoding.UTF8.GetString(b);
            if (!string.IsNullOrEmpty(postStr)) //请求处理  
            {
                Handle(postStr, context);
            }
        }
        else
        {
            Auth();
        }
    }

    public void Auth()
    {
        string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"];
        if (CheckSignature()) //校验签名是否正确  
        {
            if (!string.IsNullOrEmpty(echoStr))
            {
                System.Web.HttpContext.Current.Response.Write(echoStr); //返回原值表示校验成功  
                System.Web.HttpContext.Current.Response.End();
            }
        }
    }

    public void Handle(string postStr, HttpContext context)
    {
        //封装请求类  
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(postStr);
        XmlElement rootElement = doc.DocumentElement;
        //MsgType  
        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");
        //接收的值--->接收消息类(也称为消息推送)  
        RequestXML requestXML = new RequestXML();
        requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
        requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
        requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
        requestXML.MsgType = MsgType.InnerText;

        //根据不同的类型进行不同的处理  
        switch (requestXML.MsgType)
        {
            case "text": //文本消息  
                requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
                break;
            case "image": //图片  
                requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
                break;
            case "location": //位置  
                requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
                requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
                requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;
                requestXML.Label = rootElement.SelectSingleNode("Label").InnerText;
                break;
            case "link": //链接  
                break;
            case "event": //事件推送 支持V+  
                requestXML.Event = rootElement.SelectSingleNode("Event").InnerText;
                break;
        }

        //消息回复  
        ResponseMsg(requestXML, context);
    }


    /// <summary>  
    /// 验证微信签名  
    /// * 将token、timestamp、nonce三个参数进行字典序排序  
    /// * 将三个参数字符串拼接成一个字符串进行sha加密  
    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。  
    /// </summary>  
    /// <returns></returns>  
    private bool CheckSignature()
    {
        string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];
        string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
        string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];
        //加密/校验流程：  
        // 将token、timestamp、nonce三个参数进行字典序排序  
        string[] ArrTmp = { Token, timestamp, nonce };
        Array.Sort(ArrTmp);//字典排序  
        //将三个参数字符串拼接成一个字符串进行sha加密  
        string tmpStr = string.Join("", ArrTmp);
        tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
        tmpStr = tmpStr.ToLower();
        //开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。  
        if (tmpStr == signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>  
    /// 消息回复(微信信息返回)  
    /// </summary>  
    /// <param name="requestXML">The request XML.</param>  
    private void ResponseMsg(RequestXML requestXML, HttpContext context)
    {
        try
        {
            string resxml = "";
            string openid = requestXML.FromUserName;
            string content = string.Empty;
            string url = "http://" + context.Request.Url.Host + "/wechat/";
            switch (requestXML.MsgType)
            {
                case "text":
                    if (requestXML.Content.ToUpper() == "YGDL")
                    {
                        CookieHelper.SetObject("openid", openid);
                        //是否已激活
                        if (UserService.IsActivate(openid))
                        {
                            content = string.Format("欢迎回来！<a href='{0}emplist.html'>我的工单</a>", url);
                        }
                        else
                        {
                            content = string.Format("欢迎回来！<a href='{0}emplist.html'>员工登陆</a>", url);
                        }
                    }
                    break;
                case "location":
                    //string city = GetMapInfo(requestXML.Location_X, requestXML.Location_Y);
                    break;
                case "image":
                    //图文混合的消息 具体格式请见官方API“回复图文消息”   
                    break;
                case "event":
                    if (requestXML.Event == "subscribe")//关注事件
                    {
                        //是否已注册
                        if (MemberService.IsRegister(openid))
                        {
                            content = string.Format("欢迎关注爱尚洗车，我们为您提供优质的洗车服务！<a href='{0}default.html'>预约洗车</a>", url);
                        }
                        else
                        {
                            content = string.Format("欢迎关注爱尚洗车，我们为您提供优质的洗车服务！<a href='{0}login.html'>免费注册</a>", url); ;
                        }
                    }
                    break;
            }
            resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + content + "]]></Content><FuncFlag></FuncFlag></xml>";
            System.Web.HttpContext.Current.Response.Write(resxml);
        }
        catch (Exception ex)
        {
            //WriteTxt("异常：" + ex.Message + "Struck:" + ex.StackTrace.ToString());  
            //wx_logs.MyInsert("异常：" + ex.Message + "Struck:" + ex.StackTrace.ToString());  
        }
    }


    /// <summary>  
    /// unix时间转换为datetime  
    /// </summary>  
    /// <param name="timeStamp"></param>  
    /// <returns></returns>  
    private DateTime UnixTimeToTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }


    /// <summary>  
    /// datetime转换为unixtime  
    /// </summary>  
    /// <param name="time"></param>  
    /// <returns></returns>  
    private int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}